<script setup>
import { importChromeBookmarks, importFromJson } from '@/utils/bookmarks';
import { getFaviconUrl } from '@/utils/favicon';
import { storage } from '@/utils/storage';
import { ArrowDown, Delete, Download, Folder, Position, Search, Upload } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, ref } from 'vue';
import { useCateStore } from '@/store';

// 存储常量
const CATEGORIES_STORE = 'categories';
const URLS_STORE = 'urls';
const UI_SETTINGS_STORE = 'uiSettings';
// 状态
const categories = ref([]);
const urls = ref([]);
const currentCategory = ref('');
const newCategoryName = ref('');
const showAddCategory = ref(false);
const searchQuery = ref('');
const cateStore = useCateStore();
// 计算属性
const filteredUrls = computed(() => {
  const filtered = urls.value.filter(url => url.categoryId === currentCategory.value);

  if (!searchQuery.value) {
    return filtered;
  }

  const query = searchQuery.value.toLowerCase();
  return filtered.filter(url =>
    url.title.toLowerCase().includes(query) ||
    url.url.toLowerCase().includes(query)
  );
});



// 方法
const loadData = () => {
  storage.get([CATEGORIES_STORE, URLS_STORE, UI_SETTINGS_STORE], (result) => {
    console.log("result", result);
    if (result[CATEGORIES_STORE]) {
      categories.value = result[CATEGORIES_STORE];
      cateStore.onLoadCateList();
    } else {
      // 初始默认分类
      categories.value = [
        { id: 1, name: '默认分类' },
      ];
      saveData().catch(err => console.error('Failed to save initial data:', err));
    }

    if (result[URLS_STORE]) {
      urls.value = result[URLS_STORE];
    }
  });
};

const saveData = async () => {
  console.log('Saving data...');
  console.log('Categories:', categories.value);
  console.log('URLs:', urls.value);
  const data = {};
  data[CATEGORIES_STORE] = categories.value;
  data[URLS_STORE] = urls.value;

  const success = await storage.set(data);

  if (success) {
    console.log('Data saved successfully');
  } else {
    console.error('Failed to save data');
    ElMessage({
      type: 'error',
      message: '保存数据失败，请重试'
    });
  }
};



const addCategory = async () => {
  if (newCategoryName.value.trim()) {
    const newId = categories.value.length > 0
      ? Math.max(...categories.value.map(c => c.id)) + 1
      : 1;

    categories.value.push({
      id: newId,
      name: newCategoryName.value.trim()
    });

    newCategoryName.value = '';
    showAddCategory.value = false;
    await saveData();

    ElMessage({
      type: 'success',
      message: '添加成功'
    });
  }
};

const deleteCategory = (categoryId) => {
  ElMessageBox.confirm(
    '删除分类将同时删除该分类下的所有URL，是否继续？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    categories.value = categories.value.filter(c => c.id !== categoryId);
    urls.value = urls.value.filter(u => u.categoryId !== categoryId);

    if (currentCategory.value === categoryId) {
      currentCategory.value = categories.value[0]?.id || 0;
    }

    await saveData();
    ElMessage({
      type: 'success',
      message: '删除成功'
    });
  }).catch(() => {
    // 用户取消
  });
};

const exportData = () => {
  storage.get([CATEGORIES_STORE, URLS_STORE], (result) => {
    const data = {
      categories: result[CATEGORIES_STORE] || [],
      urls: result[URLS_STORE] || []
    };
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'url_manager_export.json';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    ElMessage({
      type: 'success',
      message: '导出成功'
    });
  });
};

// 导入所有书签
const importAllBookmarks = async (mergeMode = false) => {
  try {
    const confirmText = mergeMode ?
      '将合并浏览器书签与已有书签，确定要继续吗？' :
      '这将替换现有书签数据，确定要继续吗？';

    await ElMessageBox.confirm(
      confirmText,
      mergeMode ? '合并书签' : '导入书签',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    ElMessage({
      type: 'info',
      message: '正在导入书签，请稍候...'
    });

    const result = await importChromeBookmarks(mergeMode);

    console.log("importAllBookmarks-result", result);

    // 更新本地数据
    categories.value = result.categories;
    urls.value = result.urls;
    saveData();
    ElMessage({
      type: 'success',
      message: `成功导入 ${result.imported.categories} 个分类和 ${result.imported.urls} 个书签`
    });

  } catch (error) {
    if (error === 'cancel') {
      return; // 用户取消操作
    }

    console.error('导入书签失败:', error);
    ElMessage({
      type: 'error',
      message: `导入失败: ${error.message || '未知错误'}`
    });
  }
};


// 触发文件选择对话框
const triggerFileUpload = (mergeMode) => {
  // 创建临时文件输入元素
  const fileInput = document.createElement('input');
  fileInput.type = 'file';
  fileInput.accept = '.json';
  fileInput.style.display = 'none';

  fileInput.onchange = (event) => {
    const file = event.target.files[0];
    if (file) {
      importJsonFile(file, mergeMode);
    }
    document.body.removeChild(fileInput); // 清理DOM
  };

  document.body.appendChild(fileInput);
  fileInput.click();
};

// 导入JSON文件
const importJsonFile = async (file, mergeMode) => {
  try {
    const confirmText = mergeMode ?
      '将合并JSON文件中的书签与已有书签，确定要继续吗？' :
      '这将替换现有书签数据，确定要继续吗？';

    await ElMessageBox.confirm(
      confirmText,
      mergeMode ? '合并书签' : '导入书签',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    ElMessage({
      type: 'info',
      message: '正在读取JSON文件，请稍候...'
    });

    // 读取文件内容
    const reader = new FileReader();

    reader.onload = async (e) => {
      try {
        const jsonContent = e.target.result;

        ElMessage({
          type: 'info',
          message: '正在导入书签，请稍候...'
        });

        const result = await importFromJson(jsonContent, mergeMode);

        console.log("importJsonFile-result", result);

        // 更新本地数据
        categories.value = result.categories;
        urls.value = result.urls;
        await saveData();

        ElMessage({
          type: 'success',
          message: `成功导入 ${result.imported.categories} 个分类和 ${result.imported.urls} 个书签`
        });
      } catch (error) {
        console.error('处理JSON文件失败:', error);
        ElMessage({
          type: 'error',
          message: `处理JSON文件失败: ${error.message || '未知错误'}`
        });
      }
    };

    reader.onerror = () => {
      ElMessage({
        type: 'error',
        message: '读取文件失败'
      });
    };

    reader.readAsText(file);
  } catch (error) {
    if (error === 'cancel') {
      return; // 用户取消操作
    }

    console.error('导入JSON书签失败:', error);
    ElMessage({
      type: 'error',
      message: `导入失败: ${error.message || '未知错误'}`
    });
  }
};

// 处理导入命令
const handleImportCommand = (command) => {
  if (command === 'replace') {
    importAllBookmarks(false); // 替换模式
  } else if (command === 'merge') {
    importAllBookmarks(true); // 合并模式
  } else if (command === 'json-replace') {
    triggerFileUpload(false); // 从JSON导入（替换模式）
  } else if (command === 'json-merge') {
    triggerFileUpload(true); // 从JSON导入（合并模式）
  }
};


// 初始化
onMounted(() => {
  loadData();
});
</script>
<template>
  <div class="grid grid-cols-1 gap-4 mt-2">
    <!-- 导出导入 -->
    <div class="flex justify-end items-center gap-2">
      <el-button type="success" @click="exportData">
        <el-icon>
          <Download />
        </el-icon> 导出书签
      </el-button>
      <el-dropdown trigger="click" @command="handleImportCommand">
        <el-button type="warning">
          <el-icon>
            <Position />
          </el-icon> 导入书签
          <el-icon style="margin-left: 5px;">
            <ArrowDown />
          </el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="replace">
              <el-icon>
                <Position />
              </el-icon> 从浏览器导入（替换）
            </el-dropdown-item>
            <el-dropdown-item command="merge">
              <el-icon>
                <Position />
              </el-icon> 从浏览器导入（合并）
            </el-dropdown-item>
            <el-dropdown-item divided></el-dropdown-item>
            <el-dropdown-item command="json-replace">
              <el-icon>
                <Upload />
              </el-icon> 从JSON导入（替换）
            </el-dropdown-item>
            <el-dropdown-item command="json-merge">
              <el-icon>
                <Upload />
              </el-icon> 从JSON导入（合并）
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <!-- 分类 -->
    <el-select v-model="currentCategory" placeholder="请选择分类" class="w-full font-bold">
      <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id">
        <div class="flex justify-between items-center">
          <!-- 分类名称 -->
          <div class="flex items-center">
            <el-icon class="mr-2">
              <Folder />
            </el-icon>
            <span >{{ category.name }}</span>
          </div>
          <!-- 操作按钮 -->
          <div class="flex items-center">
            <el-button v-if="categories.length > 1" size="small" type="danger" circle
              @click.stop="deleteCategory(category.id)">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </div>
        </div>
      </el-option>
      <template #header>
        <div class="flex justify-between items-center">
          <el-input v-model="newCategoryName" size="small" placeholder="分类名称" class="rounded-button mr-2"></el-input>
          <div class="flex items-center">
            <el-button type="primary" size="small" @click="cateStore.refreshCateList" icon="Refresh">刷新</el-button>
            <el-button type="success" size="small" @click="addCategory" icon="CirclePlus">添加</el-button>
          </div>
        </div>
      </template>
    </el-select>
    <!-- 搜索 -->
    <el-input v-model="searchQuery" placeholder="搜索书签..." clearable>
      <template #prefix>
        <el-icon>
          <Search />
        </el-icon>
      </template>
    </el-input>
    <!-- 书签 -->
    <div>
      <el-empty v-if="filteredUrls.length === 0" description="当前分类下没有书签" :image-size="200">
        <template #description>
          <p>当前分类下没有书签，您可以通过导入功能添加书签</p>
        </template>
      </el-empty>
      <!-- 书签列表展示 -->
      <div v-else class="flex flex-col gap-2 h-[calc(100vh-200px)] overflow-y-auto">
        <div v-for="url in filteredUrls" :key="url.id" class="cursor-pointer flex items-center gap-2 hover:bg-gray-100 duration-300 ease-in-out">
          <img :src="getFaviconUrl(url.url)" alt="icon" class="w-4 h-4" />
          <el-link class="duration-300 ease-in-out hover:text-blue-500 font-bold" :href="url.url" target="_blank">{{ url.title }}</el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped></style>
